﻿using System;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using KPIS.GERP.ESS.APP.App_UI.Commons;
using KPIS.GERP.ESS.BLL;
//Adding
using System.Data;
using System.Collections.Generic;
using KPIS.GERP.ESS.MODEL;
using KPIS.GERP.ESS.DAL;

namespace KPIS.GERP.ESS.APP.App_UI.Forms
{
    public partial class ESS_MoneyReturns : System.Web.UI.Page
    {

        #region Fields

        Main main = new Main();
        BGM_ProjectOperationExpense.BGM_ProjectOperationExpense opexp = new BGM_ProjectOperationExpense.BGM_ProjectOperationExpense();
        FIM_MoneyRequests.FIM_MoneyRequests mr = new FIM_MoneyRequests.FIM_MoneyRequests();
        FIM_MoneyRequestDtls.FIM_MoneyRequestDtls mrd = new FIM_MoneyRequestDtls.FIM_MoneyRequestDtls();
        FIM_MAS_BorrowTypes.FIM_MAS_BorrowTypes bt = new FIM_MAS_BorrowTypes.FIM_MAS_BorrowTypes();
        BGM_MAS_Source.BGM_MAS_Source source = new BGM_MAS_Source.BGM_MAS_Source();
        B_MessageSend send = new B_MessageSend();
        D_BgmProjectOperation opexp2 = new D_BgmProjectOperation();
        FIM_MAS_Contacts.FIM_MAS_Contacts con = new FIM_MAS_Contacts.FIM_MAS_Contacts();
        BGM_MAS_ExpenseGroup.BGM_MAS_ExpenseGroup expgrp = new BGM_MAS_ExpenseGroup.BGM_MAS_ExpenseGroup();
        FIM_MoneyReturns.FIM_MoneyReturns re = new FIM_MoneyReturns.FIM_MoneyReturns();
        FIM_MoneyReturnDtls.FIM_MoneyReturnDtls red = new FIM_MoneyReturnDtls.FIM_MoneyReturnDtls();
        FIM_Employees.FIM_Employees emp = new FIM_Employees.FIM_Employees();
        MailMerge mailMerge = new MailMerge();

        #endregion

        #region Events

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                cmdArival_Click(null, null);
                LoadData();
            }
        }

        protected void LoadDDLBgmProjOperSeq()
        {
            int nBgmProjOperSeq = main.ConvertNullInt(lblBgmProjOperSeq.Text) ?? 0;
            int nMoneyReqSeq = main.ConvertNullInt(lblMoneyReqSeq.Text) ?? 0;

            ddlBgmProjOperExpSeq.DataSource = opexp2.GetAddExpenseList(nBgmProjOperSeq, nMoneyReqSeq);
            ddlBgmProjOperExpSeq.DataBind();
        }

        protected void cmdArival_Click(object sender, EventArgs e)
        {
            cmdArival.CssClass = "LinkButtonBigBorder";
            cmdHistory.CssClass = "LinkButtonBigNoBorder";

            LoadGrdViewArival();
            GrdViewArival.Visible = true;
            GrdViewHistory.Visible = false;
            PanelEdit.Visible = false;

            cmdAddExpense.Visible = true;
            cmdCancel.Visible = false;
            cmdInsertExpense.Visible = false;
            PanelAddExpense.Visible = false;
        }

        protected void cmdHistory_Click(object sender, EventArgs e)
        {
            cmdArival.CssClass = "LinkButtonBigNoBorder";
            cmdHistory.CssClass = "LinkButtonBigBorder";

            LoadGrdViewHistory();
            GrdViewArival.Visible = false;
            GrdViewHistory.Visible = true;
            PanelEdit.Visible = false;

            cmdAddExpense.Visible = true;
            cmdCancel.Visible = false;
            cmdInsertExpense.Visible = false;
            PanelAddExpense.Visible = false;
        }

        protected void GrdViewArival_ItemDataBound(object sender, GridItemEventArgs e)
        {

        }

        protected void GrdViewArival_ItemCommand(object sender, GridCommandEventArgs e)
        {
            if (e.CommandName == "Filter" || e.CommandName == "Sort" || e.CommandName == "Page")
            {
                LoadGrdViewArival();
            }
            else if (e.CommandName == "RowClick")
            {
                PanelView.Visible = false;
                PanelEdit.Visible = true;
                Panel3.Visible = false;
                SetControl1("AddNew");

                LoadRequestInfo(main.WebString(((GridDataItem)e.Item)["money_req_seq"].Text));

                cmdDelete1.Visible = false;

                LoadGrdMoneyReturnDtls();
                LoadDDLBgmProjOperSeq();
            }
        }

        protected void GrdViewHistory_ItemDataBound(object sender, GridItemEventArgs e)
        {

        }

        protected void GrdViewHistory_ItemCommand(object sender, GridCommandEventArgs e)
        {
            if (e.CommandName == "Filter" || e.CommandName == "Sort" || e.CommandName == "Page")
            {
                LoadGrdViewHistory();
            }
            else if (e.CommandName == "RowClick")
            {
                PanelView.Visible = false;
                PanelEdit.Visible = true;

                Panel3.Visible = true;
                SetControl1("Edit");

                LoadReturnInfo(main.WebString(((GridDataItem)e.Item)["money_req_seq"].Text), main.WebString(((GridDataItem)e.Item)["return_seq"].Text));
                lblRecordStatus.Text = main.WebString(((GridDataItem)e.Item)["record_status"].Text);
                //string strMessageStatus = send.GetInfoFromRefSeq(strPK, "fim_money_returns").message_status;
                //bool bCanEdit = (strRecordStatus == "W" || strRecordStatus == "R" || strMessageStatus == "0");
                bool bApprove = lblRecordStatus.Text == "A" || lblRecordStatus.Text == "P";

                cmdInsert1.Visible = false;
                cmdInsert3.Visible = !bApprove;
                cmdUpdate1.Visible = !bApprove;
                cmdUpdate3.Visible = !bApprove;
                cmdDelete1.Visible = !bApprove;
                cmdSend.Visible = !bApprove;

                grdMoneyReturnDtls.Columns.FindByUniqueName("button").Visible = !bApprove;
                LoadDDLBgmProjOperSeq();
            }
        }

        protected void grdMoneyReturnDtls_ItemDataBound(object sender, GridItemEventArgs e)
        {

        }

        protected void grdMoneyReturnDtls_ItemCommand(object sender, GridCommandEventArgs e)
        {
            if (e.CommandName == "Filter" || e.CommandName == "Sort" || e.CommandName == "Page")
            {
                LoadGrdMoneyReturnDtls();
            }
            else if (e.CommandName == "Select")
            {
                GridDataItem item = (GridDataItem)e.Item;
                lblReqAmount.Text = ((main.ConvertNullDouble(lblRemainAmount.Text) ?? 0) + (main.ConvertNullDouble(main.WebString(item["amount"].Text)) ?? 0)).ToString("#,##0.00");
                lblMoneyReqDtlsSeq.Text = main.WebString(item["money_req_dtls_seq"].Text);
                lblReturnDtlsSeq.Text = main.WebString(item["return_dtls_seq"].Text);
                lblBgmExpName.Text = main.WebString(item["bgm_exp_name"].Text);
                txtAmount.Text = main.WebString(item["amount"].Text);
                ddlVender.SelectedValue = main.WebString(item["ConId"].Text);
                txtDtlsRefNo.Text = main.WebString(item["ref_no"].Text);
                txtDtlsRefDate.SetValue(main.WebString(item["ref_date"].Text));
                txtBranchNo.Text = main.WebString(item["branch_no"].Text);

                PanelOpacity.Visible = true;
                PanelMoneyReturnDtls.Visible = true;

                bool bEdit = lblReturnDtlsSeq.Text.Length > 0;
                cmdInsert3.Visible = !bEdit;
                cmdUpdate3.Visible = bEdit;
            }
        }

        protected void cmdInsert1_Click(object sender, EventArgs e)
        {
            if (!ChackData1())
            {
                main.MessageAlert(Page, "กรอกข้อมูลให้ครบถ้วน");
                return;
            }

            FIM_MoneyReturns.M_FIM_MoneyReturns info = new FIM_MoneyReturns.M_FIM_MoneyReturns();
            info.return_date = dpReturnDate.GetDateValue();
            info.money_req_seq = main.ConvertNullInt(lblMoneyReqSeq.Text);
            info.ref_no = re.GenerateNextMoneyReturnsRefNo(!string.IsNullOrEmpty(lblBgmSourceSeq.Text) ? (lblBgmSourceSeq.Text == "1" ? "1" : "2") : "");

            info.record_status = "W";
            info.created_by = main.ConvertNullInt(Session["EmpSeq"]);
            info.created_when = DateTime.Today;

            lblReturnSeq.Text = re.Insert(info);

            Panel3.Visible = true;
            cmdInsert1.Visible = false;
            cmdUpdate1.Visible = true;
            LoadGrdMoneyReturnDtls();
            lblReturnRefNo.Text = info.ref_no;
        }

        protected void cmdUpdate1_Click(object sender, EventArgs e)
        {
            if (!ChackData1())
            {
                main.MessageAlert(Page, "กรอกข้อมูลให้ครบถ้วน");
                return;
            }

            FIM_MoneyReturns.M_FIM_MoneyReturns info = new FIM_MoneyReturns.M_FIM_MoneyReturns();
            info.return_seq = Convert.ToInt32(lblReturnSeq.Text);
            info.return_date = dpReturnDate.GetDateValue();
            info.money_req_seq = main.ConvertNullInt(lblMoneyReqSeq.Text);
            info.ref_no = lblReturnRefNo.Text;

            info.updated_by = main.ConvertNullInt(Session["EmpSeq"]);
            info.updated_when = DateTime.Today;

            re.Update(info);
        }

        protected void cmdCancel1_Click(object sender, EventArgs e)
        {
            PanelEdit.Visible = false;
            PanelView.Visible = true;
        }

        protected void cmdInsert3_Click(object sender, EventArgs e)
        {
            try
            {
                if (!ChackData3())
                {
                    
                    return;
                }

                FIM_MoneyReturnDtls.M_FIM_MoneyReturnDtls info = new FIM_MoneyReturnDtls.M_FIM_MoneyReturnDtls();

                info.return_seq = main.ConvertNullInt(lblReturnSeq.Text);
                info.money_req_dtls_seq = main.ConvertNullInt(lblMoneyReqDtlsSeq.Text);
                info.amount = main.ConvertNullDouble(txtAmount.Text);
                info.vat_amount = main.ConvertNullDouble(txtVatAmount.Text);
                info.ConId = main.ConvertNullInt(ddlVender.SelectedValue.ToString());
                info.ref_no = txtDtlsRefNo.Text;
                info.ref_date = dpReturnDate.GetDateValue();
                info.branch_no = txtBranchNo.Text;

                info.record_status = "W";
                info.created_by = main.ConvertNullInt(Session["EmpSeq"]);
                info.created_when = DateTime.Today;

                red.Insert(info);

                PanelMoneyReturnDtls.Visible = false;
                PanelOpacity.Visible = false;
                LoadGrdMoneyReturnDtls();
                ClearControl3();
            }
            catch (Exception ex)
            {

                throw ex;
            }

        }

        protected void cmdUpdate3_Click(object sender, EventArgs e)
        {
            if (!ChackData3())
            {
                main.MessageAlert(Page, txtAmount.Text.Trim().Length == 0 ? "กรอกข้อมูลให้ครบถ้วน" : "จำนวนเงินที่หักล้างไม่ถูกต้อง");
                return;
            }

            FIM_MoneyReturnDtls.M_FIM_MoneyReturnDtls info = new FIM_MoneyReturnDtls.M_FIM_MoneyReturnDtls();
            info.return_dtls_seq = Convert.ToInt32(lblReturnDtlsSeq.Text);
            info.return_seq = main.ConvertNullInt(lblReturnSeq.Text);
            info.money_req_dtls_seq = main.ConvertNullInt(lblMoneyReqDtlsSeq.Text);
            info.amount = main.ConvertNullDouble(txtAmount.Text);
            info.vat_amount = main.ConvertNullDouble(txtVatAmount.Text);
            info.ConId = main.ConvertNullInt(ddlVender.SelectedValue.ToString());
            info.ref_no = txtDtlsRefNo.Text;
            info.ref_date = dpReturnDate.GetDateValue();
            info.branch_no = txtBranchNo.Text;

            info.updated_by = main.ConvertNullInt(Session["EmpSeq"]);
            info.updated_when = DateTime.Today;

            red.Update(info);

            PanelMoneyReturnDtls.Visible = false;
            PanelOpacity.Visible = false;
            LoadGrdMoneyReturnDtls();
            ClearControl3();
        }

        protected void cmdCancel3_Click(object sender, EventArgs e)
        {
            PanelMoneyReturnDtls.Visible = false;
            PanelOpacity.Visible = false;
            ClearControl3();
        }

        protected void cmdDelete1_Click(object sender, EventArgs e)
        {
            FIM_MoneyReturns.M_FIM_MoneyReturns info = new FIM_MoneyReturns.M_FIM_MoneyReturns();
            info.return_seq = Convert.ToInt32(lblReturnSeq.Text);
            info.updated_by = main.ConvertNullInt(Session["EmpSeq"]);
            info.updated_when = DateTime.Now;

            re.Delete(info);
            PanelEdit.Visible = false;
            PanelView.Visible = true;
            LoadGrdViewHistory();
            main.MessageAlert(Page, "ลบรายการเรียบร้อย");
        }

        protected void RepeaterReturnExpense_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item is RepeaterItem)
            {
                if (e.Item.ItemType != ListItemType.Header)
                {
                }
            }
        }

        protected void RepeaterReturnExchange_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item is RepeaterItem)
            {
                if (e.Item.ItemType == ListItemType.Footer)
                {
                }
            }
        }

        protected void cmdManual_Click(object sender, EventArgs e)
        {
            LinkButton cmd = (LinkButton)sender;
            RepeaterItem item = (RepeaterItem)((LinkButton)sender).Parent;
            RadNumericTextBox txtExchangeRate2 = (RadNumericTextBox)item.FindControl("txtExchangeRate");

            txtExchangeRate2.Text = cmd.Text;
            cmd.Visible = false;
            txtExchangeRate2.Visible = true;
        }

        protected void cmdApprove_Click(object sender, EventArgs e)
        {
            re.ChangeStatus(lblReturnSeq.Text, "A", Session["EmpSeq"].ToString());
            PanelView.Visible = true;
            PanelEdit.Visible = false;
            LoadGrdViewHistory();
            main.MessageAlert(Page, "บันทึกเรียบร้อยแล้ว");
        }

        protected void cmdUnApprove_Click(object sender, EventArgs e)
        {
            re.ChangeStatus(lblReturnSeq.Text, "W", Session["EmpSeq"].ToString());
            PanelView.Visible = true;
            PanelEdit.Visible = false;
            LoadGrdViewHistory();
            main.MessageAlert(Page, "บันทึกเรียบร้อยแล้ว");
        }

        protected void cmdSend_Click(object sender, EventArgs e)
        {
            var model = re.GetInfo(lblReturnSeq.Text);
            double dReturnAmountAcum = model.total_bath_amount_accum ?? 0;
            double dRequestAmount = model.money_req_total_bath_amount ?? 0;

            if ((dReturnAmountAcum * 100) / dRequestAmount < 75 && txtRemarks.Text.Trim().Length == 0)
            {
                main.MessageAlert(Page, "ค่าใช้จ่ายทั้งหมดไม่ถึง 75% ของเงินที่ยืม ต้องบันทึกหมายเหตุด้วย");
                return;
            }
            else if (dReturnAmountAcum <= 0)
            {
                main.MessageAlert(Page, "ไม่สามารถส่งรายการได้เนื่องจากจำนวนเงินในรายการเป็น 0");
                return;
            }

            FIM_MoneyReturns.M_FIM_MoneyReturns info = new FIM_MoneyReturns.M_FIM_MoneyReturns();
            info.return_seq = Convert.ToInt32(lblReturnSeq.Text);
            info.return_date = dpReturnDate.GetDateValue();
            info.money_req_seq = main.ConvertNullInt(lblMoneyReqSeq.Text);
            info.ref_no = lblReturnRefNo.Text;
            info.remarks = txtRemarks.Text;
            info.record_status = "P";
            info.updated_by = main.ConvertNullInt(Session["EmpSeq"]);
            info.updated_when = DateTime.Today;
            re.Update(info);

            re.ChangeStatus(lblReturnSeq.Text, "P", Session["EmpSeq"].ToString());

            // Edit by Aek 2014-07-29
            // Calculate base on to_emp_seq field in table message_send, not login session 
            int nUpperEmpSeq = main.ConvertNullInt(send.GetCurrentApprover(SsMng.EmpSeq, null, "FIM_MONEY_REQUESTS", 1).Rows[0]["emp_seq"].ToString()) ?? 0;
            M_MessageSend sendInfo = new M_MessageSend
            {
                send_date = DateTime.Today,
                ref_seq = Convert.ToInt32(lblReturnSeq.Text),
                ref_type = "fim_money_returns",
                ref_no = lblReturnRefNo.Text,
                send_text = "แจ้งการชดใช้เงินเลขที่ใบยืม " + model.borrow_no,
                from_emp_seq = SsMng.EmpSeqI,
                to_emp_seq = nUpperEmpSeq,

                from_pos_seq = emp.GetInfo(SsMng.EmpSeq).pos_seq,
                to_pos_seq = emp.GetInfo(nUpperEmpSeq.ToString()).pos_seq,

                from_send_seq = null,
                remarks = txtRemarks.Text,
                approve_path_seq = null,
                message_status = "0",
                record_status = "W",
                created_by = SsMng.EmpSeqI,
                created_when = DateTime.Now,
            };

            M_MessageSend sendInfo1 = new M_MessageSend
            {
                send_date = DateTime.Today,
                ref_seq = Convert.ToInt32(lblReturnSeq.Text),
                ref_type = "fim_money_returns",
                ref_no = lblReturnRefNo.Text,
                send_text = "แจ้งการชดใช้เงินเลขที่ใบยืม " + model.borrow_no,
                from_emp_seq = SsMng.EmpSeqI,
                to_emp_seq = 22,// hardcode

                from_pos_seq = emp.GetInfo(SsMng.EmpSeq).pos_seq,
                to_pos_seq = emp.GetInfo("22").pos_seq,// hardcode

                from_send_seq = null,
                remarks = txtRemarks.Text,
                approve_path_seq = null,
                message_status = "0",
                record_status = "W",
                created_by = SsMng.EmpSeqI,
                created_when = DateTime.Now,
            };

            send.Insert(sendInfo);
            send.Insert(sendInfo1);

            PanelView.Visible = true;
            PanelEdit.Visible = false;
            LoadGrdViewHistory();
            main.MessageAlert(Page, "บันทึกเรียบร้อยแล้ว");
        }

        protected void cmdPrintForm_Click(object sender, EventArgs e)
        {
            //Adding by Raksakaew on Feb 24,2014
            if (lblMoneyReqSeq.Text.Trim() != "")
            {
                string strMoneyReqSeq = lblMoneyReqSeq.Text.Trim();
                DAL.D_FimMoneyReturn re2 = new DAL.D_FimMoneyReturn();

                cmdPrintForm.PostBackUrl = string.Format("~/App_UI/Forms/frmGetDocxReport.aspx/?arg1={0}&arg2={1}&arg3={2}&arg4={3}", "R", strMoneyReqSeq, lblReturnSeq.Text.Trim(),lblReturnRefNo.Text.Trim());

                /*
                DataTable dtbMain = re2.getMoneyReturnReport(strMoneyReqSeq);
                DataTable dtbSub = ConvertToDataTable(red.GetMoneyReqDtls(lblReturnSeq.Text.Trim(), strMoneyReqSeq));
                              
                Dictionary<string, string> fields = new Dictionary<string, string>();

                if (dtbMain.Rows.Count > 0)
                {
                    DataRow dr = dtbMain.Rows[0];

                    fields.Add("DebtorJobsiteName", dr["debtor_job_site_name"].ToString());
                    fields.Add("BorrowNo", dr["borrow_no"].ToString());
                    fields.Add("ReturnDate", main.ConvertNullDateTime(dr["return_date"]) != null
                                             ? main.ConvertNullDateTime(dr["return_date"]).Value.ToShortDateString() : "");
                    fields.Add("MoneyReqDate", main.ConvertNullDateTime(dr["money_req_date"]) != null
                                             ? main.ConvertNullDateTime(dr["money_req_date"]).Value.ToShortDateString() : "");
                    fields.Add("BorrowStartDate", main.ConvertNullDateTime(dr["borrow_start_date"]) != null
                                                ? main.ConvertNullDateTime(dr["borrow_start_date"]).Value.ToShortDateString() : "");
                    fields.Add("BorrowEndDate", main.ConvertNullDateTime(dr["borrow_end_date"]) != null
                                             ? main.ConvertNullDateTime(dr["borrow_end_date"]).Value.ToShortDateString() : "");
                    fields.Add("SumAmountRtn", main.ConvertNullDouble(dr["sum_amount_rtn"]) != null
                                            ? main.ConvertNullDouble(dr["sum_amount_rtn"]).Value.ToString("#,##0.00") : "0.00");
                    fields.Add("RefNo", dr["ref_no"].ToString());
                    fields.Add("BorrowReturnDate", main.ConvertNullDateTime(dr["borrow_return_date"]) != null
                                                 ? main.ConvertNullDateTime(dr["borrow_return_date"]).Value.ToShortDateString() : "");
                    fields.Add("DebtorName", dr["debtor_name"].ToString());                                       
                    fields.Add("MoneyReqName", dr["money_req_name"].ToString());                    
                    fields.Add("RefNoRQ", dr["ref_no_rq"].ToString());
                    fields.Add("BgmProjOperCode", dr["bgm_proj_oper_code"].ToString());
                    fields.Add("BgmProjOperName", dr["bgm_proj_oper_name"].ToString());                   
                    fields.Add("MoneyTextThai", mailMerge.ThaiBaht(dr["sum_amount_rtn"].ToString()));
                    fields.Add("EmpName", dr["emp_name"].ToString());
                    fields.Add("JobSiteName", dr["debtor_job_site_name"].ToString());
                    
                }

                Dictionary<string, DataTable> Table = new Dictionary<string, DataTable>();
                Table.Add("table1", dtbSub);

                string strTemplatePath = Server.MapPath("~/App_UI/Reports/Templates/แบบฟอร์ม_คืนเงิน.docx");
                string strSaveAsFileName = string.Format("แบบฟอร์ม_คืนเงิน{0}.docx", DateTime.Now.ToString("yyyyMMddHHmmssffff"));
                string strSaveAsPath = Server.MapPath("~/App_UI/Reports/Temp/");

                if (mailMerge.MergeTemplate(strTemplatePath, strSaveAsPath + strSaveAsFileName, fields, Table, null, null))
                {
                    mailMerge.SaveFileToClient(Response, strSaveAsPath, strSaveAsFileName, false);
                }
                */
            }
        }

        protected void cmdAddExpense_Click(object sender, EventArgs e)
        {
            cmdAddExpense.Visible = false;
            cmdCancel.Visible = true;
            cmdInsertExpense.Visible = true;
            PanelAddExpense.Visible = true;
        }

        protected void cmdInsertExpense_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(ddlBgmProjOperExpSeq.SelectedValue))
            {
                main.MessageAlert(Page, "กรุณาเลือกค่าใช้จ่ายที่ต้องการเพิ่ม");
                return;
            }

            var model = new FIM_MoneyRequestDtls.M_FIM_MoneyRequestDtls
            {
                money_req_seq = main.ConvertNullInt(lblMoneyReqSeq.Text),
                money_req_dtls_name = "",
                bgm_proj_oper_exp_seq = main.ConvertNullInt(ddlBgmProjOperExpSeq.SelectedValue),
                amount_vat = 0,
                amount_tax = 0,
                amount_fund = 0,
                percent_vat = 0,
                percent_tax = 0,
                amount = 0,
                record_status = SystemInfo._ActiveRecordStatus,
                created_by = SsMng.EmpSeqI,
                created_when = DateTime.Now
            };

            mrd.Insert(model);
            LoadGrdMoneyReturnDtls();
            LoadDDLBgmProjOperSeq();

            cmdAddExpense.Visible = true;
            cmdCancel.Visible = false;
            cmdInsertExpense.Visible = false;
            PanelAddExpense.Visible = false;
        }

        protected void cmdCancel_Click(object sender, EventArgs e)
        {
            cmdAddExpense.Visible = true;
            cmdCancel.Visible = false;
            cmdInsertExpense.Visible = false;
            PanelAddExpense.Visible = false;
        }
        #endregion

        #region Protected Methods

        protected void LoadGrdViewArival()
        {
            try
            {
                var data = mr.GetNotReturnList(null, Session["EmpSeq"].ToString(), null);
                GrdViewArival.DataSource = data;
                GrdViewArival.DataBind();
            }
            catch (Exception ex)
            {
                RadAjaxManager.GetCurrent(Page).Alert(ex.Message);
            }
        }

        protected void LoadGrdViewHistory()
        {
            try
            {
                var data = re.GetFull(null, null, null, null, Session["EmpSeq"].ToString(), null, false);
                GrdViewHistory.DataSource = data;
                GrdViewHistory.DataBind();
            }
            catch (Exception ex)
            {
                RadAjaxManager.GetCurrent(Page).Alert(ex.Message);
            }
        }

        protected void LoadRequestInfo(string strMoneyReqSeq)
        {
            FIM_MoneyRequests.M_FIM_MoneyRequests mrInfo = mr.GetInfo(strMoneyReqSeq);
            lblMoneyReqSeq.Text = strMoneyReqSeq;
            lblMoneyReqName.Text = mrInfo.money_req_name;
            lblBorrowNo.Text = mrInfo.borrow_no;
            lblBorrowReturnDate.Text = (mrInfo.borrow_return_date != null ? mrInfo.borrow_return_date.Value.ToShortDateString() : "-");
            txtRemarks.Text = mrInfo.remarks;
            dpReturnDate.SetValue(DateTime.Today);
            lblReturnRefNo.Text = "-";
            lblReturnSeq.Text = "";
            lblBgmSourceSeq.Text = (mrInfo.bgm_source_seq ?? 1).ToString();
            lblBgmProjOperSeq.Text = mrInfo.bgm_proj_oper_seq.ToString();
            lblBgmExpGrpSeq.Text = mrInfo.bgm_exp_grp_seq.ToString();

            //Panel3.Visible = true;
            //LoadGrdMoneyReturnDtls();
        }

        protected void LoadReturnInfo(string strMoneyReqSeq, string strReturnSeq)
        {
            FIM_MoneyRequests.M_FIM_MoneyRequests mrInfo = mr.GetInfo(strMoneyReqSeq);
            lblMoneyReqSeq.Text = strMoneyReqSeq;
            lblMoneyReqName.Text = mrInfo.money_req_name;
            lblBorrowNo.Text = mrInfo.borrow_no;
            lblBorrowReturnDate.Text = (mrInfo.borrow_return_date != null ? mrInfo.borrow_return_date.Value.ToShortDateString() : "-");
            txtRemarks.Text = mrInfo.remarks;
            lblBgmProjOperSeq.Text = mrInfo.bgm_proj_oper_seq.ToString();
            lblBgmExpGrpSeq.Text = mrInfo.bgm_exp_grp_seq.ToString();

            lblReturnSeq.Text = strReturnSeq;
            lblBgmSourceSeq.Text = (mrInfo.bgm_source_seq ?? 1).ToString();
            LoadGrdMoneyReturnDtls();

            GridDataItem item = ((GridDataItem)GrdViewHistory.SelectedItems[0]);
            dpReturnDate.SetValue(main.WebString(item["return_date"].Text));
            lblReturnRefNo.Text = main.WebString(item["ref_no"].Text);
            lblReturnSeq.Text = main.WebString(item["return_seq"].Text);
        }

        protected void LoadGrdMoneyReturnDtls()
        {
            string strReturnSeq = lblReturnSeq.Text;

            var data = red.GetMoneyReqDtls(strReturnSeq, lblMoneyReqSeq.Text);

            grdMoneyReturnDtls.DataSource = data;
            grdMoneyReturnDtls.DataBind();

            if (lblReturnSeq.Text.Length > 0)
            {
                FIM_MoneyReturns.M_FIM_MoneyReturns info = re.GetInfo(lblReturnSeq.Text);
                lblSumReturnBathAmount.Text = (info.total_bath_amount_accum.Value).ToString("#,##0.00");
                lblSumBorrowBathAmount.Text = (info.money_req_total_bath_amount.Value).ToString("#,##0.00");
                lblSumReceiveBathAmount.Text = (info.receive_bath_amount.Value).ToString("#,##0.00");
                lblRemainAmount.Text = ((info.money_req_total_bath_amount ?? 0) - (info.total_bath_amount_accum ?? 0) - (info.receive_bath_amount ?? 0)).ToString("#,###.00");
            }
            else
            {
                FIM_MoneyRequests.M_FIM_MoneyRequests info = mr.GetInfo(lblMoneyReqSeq.Text);
                lblSumReturnBathAmount.Text = (info.return_amount ?? 0).ToString("#,##0.00");
                lblSumBorrowBathAmount.Text = (info.total_amount ?? 0).ToString("#,##0.00");
                lblSumReceiveBathAmount.Text = (info.receive_amount ?? 0).ToString("#,##0.00");
                lblRemainAmount.Text = ((info.total_amount ?? 0) - (info.return_amount ?? 0) - (info.receive_amount ?? 0)).ToString("#,###.00");
            }
        }

        protected void SetControl1(string strCommand)
        {
            switch (strCommand)
            {
                case "AddNew":
                    cmdInsert1.Visible = true;
                    cmdUpdate1.Visible = false;

                    lblModeName.Text = "เพิ่มรายการใหม่";
                    lblMode.Text = "A";
                    break;
                case "Edit":
                    cmdInsert1.Visible = false;
                    cmdUpdate1.Visible = true;
                    //cmdAddNew2.Visible = true;

                    lblModeName.Text = "แก้ไขรายการ";
                    lblMode.Text = "E";
                    break;
            }
        }

        protected bool ChackData1()
        {
            bool bOK = dpReturnDate.GetDateValue() != null;

            return bOK;
        }

        protected bool ChackData3()
        {
            bool bOK = true;

            double dAmount = main.ConvertNullDouble(txtAmount.Text) ?? 0;
            double dRemainAmount = main.ConvertNullDouble(lblReqAmount.Text) ?? 0;

            if (dAmount < 0)
            {
                main.MessageAlert(Page, "กรอกข้อมูลให้ครบถ้วน");
                bOK = false;
            }
            else if (dAmount > dRemainAmount)
            {
                main.MessageAlert(Page, "จำนวนเงินที่หักล้างไม่ถูกต้อง");
                bOK = false;
            }
            else if ((main.ConvertNullDouble(txtVatAmount.Text) ?? 0) > 0 && (string.IsNullOrEmpty(ddlVender.SelectedValue)
                || string.IsNullOrEmpty(txtBranchNo.Text) || string.IsNullOrEmpty(txtDtlsRefNo.Text) || txtDtlsRefDate.GetDateValue() == null))
            {
                main.MessageAlert(Page, "กรอกข้อมูลใบกำกับภาษีให้ครบถ้วน");
                bOK = false;
            }

            return bOK;
        }

        protected void ClearControl3()
        {
            txtAmount.Text = "";
            txtVatAmount.Text = "";
        }

        #endregion

        #region Public Methods

        public DataTable ConvertToDataTable<T>(IList<T> data)
        {
          System.ComponentModel.PropertyDescriptorCollection properties =
               System.ComponentModel.TypeDescriptor.GetProperties(typeof(T));
            DataTable table = new DataTable();
            foreach (System.ComponentModel.PropertyDescriptor prop in properties)
                table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
            foreach (T item in data)
            {
                DataRow row = table.NewRow();
                foreach (System.ComponentModel.PropertyDescriptor prop in properties)
                    row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
                table.Rows.Add(row);
            }
            return table;

        }

        public void LoadData()
        {
            IList<KPIS.GERP.GFMS.MODEL.M_FIM_MAS_Contacts> infolist = null;
            KPIS.GERP.GFMS.MODEL.M_FIM_MAS_Contacts con = new KPIS.GERP.GFMS.MODEL.M_FIM_MAS_Contacts();

            infolist = GetListVender();

            ddlVender.DataSource = infolist;
            ddlVender.DataBind();

            main.InsertEmptyDDLSelect(ddlVender);
            ddlVender.SelectedIndex = 0;
        }

        public IList<KPIS.GERP.GFMS.MODEL.M_FIM_MAS_Contacts> GetListVender()
        {
            System.Data.DataTable dt = new System.Data.DataTable();
            IList<KPIS.GERP.GFMS.MODEL.M_FIM_MAS_Contacts> infoList = new List<KPIS.GERP.GFMS.MODEL.M_FIM_MAS_Contacts>();
            string strConn = System.Web.Configuration.WebConfigurationManager.AppSettings["ConnectionString"];
            string qry = "SELECT * FROM IcmMasContact WHERE RecordStatus <> 'D' ORDER BY NameTh";

            using (System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(strConn))
            {
                if (con.State == ConnectionState.Closed)
                {
                    con.Open();
                }

                using (System.Data.SqlClient.SqlDataAdapter adp = new System.Data.SqlClient.SqlDataAdapter(qry, con))
                {
                    adp.Fill(dt);
                }
            }

            foreach (DataRow row in dt.Rows)
            {
                KPIS.GERP.GFMS.MODEL.M_FIM_MAS_Contacts info = new KPIS.GERP.GFMS.MODEL.M_FIM_MAS_Contacts();

                info.contact_seq = int.Parse(row["ConId"].ToString());
                info.contact_name = row["NameTh"].ToString();

                infoList.Add(info);
            }

            return infoList;
        }
        #endregion
        
    }
}
